package com.tjmc.tiomsresource.utils;

import org.apache.tools.zip.ZipEntry;
import org.apache.tools.zip.ZipFile;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import java.io.*;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;

/**
 * @author Luc
 * @version 1.0
 * @date 2020-05-14 13:58
 * 解压包工具
 */

@Component
public class UnZipUtils {

    private static Logger logger = LoggerFactory.getLogger(UnZipUtils.class);

    public List<File> unZip(File zipFile, String outDir) throws IOException {
        File outFileDir = new File(outDir);
        if (!outFileDir.exists()) {
            boolean isMakDir = outFileDir.mkdirs();
            if (isMakDir) {
                logger.info("创建压缩目录成功");
            }
        }
        logger.info("====Unzip:" + zipFile.getAbsolutePath());
        ZipFile zip = new ZipFile(zipFile);
        List<File> unZipFiles = new ArrayList<>();
        for (Enumeration enumeration = zip.getEntries(); enumeration.hasMoreElements(); ) {
            ZipEntry entry = (ZipEntry) enumeration.nextElement();
            String zipEntryName = entry.getName();
            InputStream in = zip.getInputStream(entry);

            if (entry.isDirectory()) {      //处理压缩文件包含文件夹的情况
                File fileDir = new File(outDir + zipEntryName);
                fileDir.mkdir();
                continue;
            }

            File file = new File(outDir, zipEntryName);
            file.createNewFile();
            OutputStream out = new FileOutputStream(file);
            byte[] buff = new byte[1024];
            int len;
            while ((len = in.read(buff)) > 0) {
                out.write(buff, 0, len);
            }
            in.close();
            out.close();
            logger.info("====Unzip:" + zipFile.getAbsolutePath() + ", success");
            unZipFiles.add(file);
        }
        return unZipFiles.size()>0?unZipFiles:null;
    }
}